<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['attacheList', 'companyList', 'attache', 'company'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     *  获取管理专员列表
     */
    public function attache()
    {
        $attacheList = \think\Db::name('auth_group_access')->where('group_id', ATTACHE_GROUP_ID)->field('uid as id')->select();
        $jsonlist = array();
        foreach ($attacheList as $key => $item) {
            $nickname = \think\Db::name('admin')->where('id', $item['id'])->value('nickname');
            if ($nickname != null)
                $jsonlist[] = ['id' => $item['id'], 'name' => $nickname];
//                $attacheList[$key]['name'] = $nickname;
        }
        return json(['list' => $jsonlist, 'total' => count($jsonlist)]);
    }

    /**
     *  获取管理专员列表json格式
     */
    public function attacheList()
    {
        $where = array();
        if ($this->auth->getGroupId() == ATTACHE_GROUP_ID) {
            $user = $this->auth->getUserInfo();
            $jsonlist = [$user['id'] => $user['nickname']];
        } else {
            $datalist = \think\Db::name('auth_group_access')->where('group_id', ATTACHE_GROUP_ID)->field('uid as id')->select();
            $jsonlist = array();
            foreach ($datalist as $item) {
                $nickname = \think\Db::name('admin')->where('id', $item['id'])->value('nickname');
                if ($nickname != null)
                    $jsonlist[$item['id']] = $nickname;
            }
        }
        return json($jsonlist);
    }

    /**
     *  获取厂商列表
     */
    public function company()
    {
//        //设置过滤方法
//        $this->request->filter(['strip_tags', 'htmlspecialchars']);
//
//        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
//        //当前页
//        $page = $this->request->request("pageNumber");
//        //分页大小
//        $pagesize = $this->request->request("pageSize");
//        //搜索条件
//        $andor = $this->request->request("andOr", "and", "strtoupper");
//        //排序方式
//        $orderby = (array) $this->request->request("orderBy/a");
//        //显示的字段
//        $field = $this->request->request("showField");
//        //主键
//        $primarykey = $this->request->request("keyField");
//        //主键值
//        $primaryvalue = $this->request->request("keyValue");
//        //搜索字段
//        $searchfield = (array) $this->request->request("searchField/a");
//        //自定义搜索条件
//        $custom = (array) $this->request->request("custom/a");
//        $order = [];
//        foreach ($orderby as $k => $v) {
//            $order[$v[0]] = $v[1];
//        }
//        $field = $field ? $field : 'name';
//
//        //如果有primaryvalue,说明当前是初始化传值
//        if ($primaryvalue !== null) {
//            $where = [$primarykey => ['in', $primaryvalue]];
//        } else {
//            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
//                $logic = $andor == 'AND' ? '&' : '|';
//                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
//                foreach ($word as $k => $v) {
//                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
//                }
//                if ($custom && is_array($custom)) {
//                    foreach ($custom as $k => $v) {
//                        $query->where($k, '=', $v);
//                    }
//                }
//            };
//        }
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            $this->model->where($this->dataLimitField, 'in', $adminIds);
//        }
//        $list = [];
//        $total = $this->model->where('group_id', COMPANY_GROUP_ID)->where($where)->count();
//        if ($total > 0) {
//            if (is_array($adminIds)) {
//                $this->model->where($this->dataLimitField, 'in', $adminIds);
//            }
//            $datalist = \think\Db::name('auth_group_access')
//                ->where('group_id', COMPANY_GROUP_ID)
//                ->where($where)
//                ->order($order)
//                ->page($page, $pagesize)
//                ->field('uid as id')
//                ->select();
//            foreach ($datalist as $index => $item) {
//                unset($item['password'], $item['salt']);
//                $list[] = [
//                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
//                    $field => isset($item[$field]) ? $item[$field] : ''
//                ];
//            }
//        }
        $jsonlist = array();
        if ($word[0] != '') {
            $log = \think\Db::name('company')->find($word[0]);
//            dump($log);
            if ($log)
                $jsonlist[] = ['id' => $log['admin_id'], 'name' => $log['title']];
//        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
//        return json(['list' => $list, 'total' => $total]);


        } else {
            $datalist = \think\Db::name('auth_group_access')
                ->where('group_id', COMPANY_GROUP_ID)
//                    ->order($order)
//                    ->page($page, $pagesize)
                ->field('uid as id')
                ->select();
            foreach ($datalist as $key => $item) {
                $nickname = \think\Db::name('company')->where('admin_id', $item['id'])->value('title');
                if ($nickname != null)
                    $jsonlist[] = ['id' => $item['id'], 'name' => $nickname];
            }
        }

        return json(['list' => $jsonlist, 'total' => count($jsonlist)]);
    }

    /**
     *  获取厂商列表json格式
     */
    public function companyList()
    {
        $where = array();
        if ($this->auth->getGroupId() == COMPANY_GROUP_ID) {
            $user = $this->auth->getUserInfo();
            $jsonlist = [$user['id'] => $user['nickname']];
        } else {
            $datalist = \think\Db::name('auth_group_access')->where('group_id', COMPANY_GROUP_ID)->field('uid as id')->select();
            $jsonlist = array();
            foreach ($datalist as $item) {
                $nickname = \think\Db::name('company')->where('admin_id', $item['id'])->value('title');
                if ($nickname != null)
                    $jsonlist[$item['id']] = $nickname;
            }
        }
//        return json(['list' => $jsonlist, 'total' => count($jsonlist)]);
        return json($jsonlist);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']]))
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post("group/a");

                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
                    'email' => 'require|email|unique:admin,email,' . $row->id
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

}
